package com.eco.fanliapp.service.impl;

import com.eco.fanliapp.common.constant.WechatConfig;
import com.eco.fanliapp.service.IDwzService;
import com.eco.fanliapp.service.RedisTemplateService;
import com.eco.fanliapp.utils.BaiduDwzUtils;
import com.eco.fanliapp.utils.MrwSoDwzUtils;
import com.eco.fanliapp.utils.SuoImDwzUtils;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
public class DwzServiceImpl implements IDwzService {
    final static String CREATE_API = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=";
    final static String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    final static String ACCESS_TOKEN_REDIS ="redis_dwz_access_token";

    final static String APPID_DWZ = "wxe1ce9f5f4c7f403a";
    final static String APPSECRET_DWZ = "b1a54024995cefa2bee6784844242548";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 创建短网址wxe1ce9f5f4c7f403a
     *b1a54024995cefa2bee6784844242548
     * @param longUrl
     *            长网址：即原网址
     *        termOfValidity
     *            有效期：默认值为long-term
     * @return  成功：短网址
     *          失败：返回空字符串
     */
    private  String createShortUrl(String longUrl) {
        try {
            String accessToken = getAccessToken();
            String requestUrl = CREATE_API+accessToken;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("action", "long2short");
            jsonObject.put("long_url", longUrl);
            String shortUrls = post(jsonObject, requestUrl);
            DwzServiceImpl.UrlResponse urlResponse = new Gson().fromJson(shortUrls, DwzServiceImpl.UrlResponse.class);

            if (urlResponse.getErrcode() == 0 || "ok".equals(urlResponse.getErrmsg())) {
                return urlResponse.getShort_url();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 获取公众号access_token
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public String getAccessToken() throws IOException {
        String accessToken = null;
        if(stringRedisTemplate.hasKey(ACCESS_TOKEN_REDIS)){
            accessToken =  stringRedisTemplate.opsForValue().get(ACCESS_TOKEN_REDIS);
        }
        if(accessToken == null || "".equals(accessToken)){
            String url = ACCESS_TOKEN_URL.replace("APPID",APPID_DWZ).replace("APPSECRET",APPSECRET_DWZ);
            JSONObject jsonObject = doGetStr(url);
            if(jsonObject!=null){
                accessToken = jsonObject.getString("access_token");
            }
            stringRedisTemplate.opsForValue().set(ACCESS_TOKEN_REDIS,accessToken,60 * 5, TimeUnit.SECONDS);//TimeUnit.SECONDS
        }
        return accessToken;
    }
    /**
     * get请求
     * @param url
     * @return
     * @throws ParseException
     * @throws IOException
     */
    private  JSONObject doGetStr(String url) throws ParseException, IOException{
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        JSONObject jsonObject = null;
        HttpResponse httpResponse = client.execute(httpGet);
        HttpEntity entity = httpResponse.getEntity();
        if(entity != null){
            String result = EntityUtils.toString(entity,"UTF-8");
            jsonObject = JSONObject.fromObject(result);
        }
        httpGet.releaseConnection();
        return jsonObject;
    }
    private  String post(JSONObject json, String url){
        String result = "";
        HttpPost post = new HttpPost(url);
        try{
            CloseableHttpClient httpClient = HttpClients.createDefault();

            post.setHeader("Content-Type","application/json;charset=utf-8");
            post.addHeader("Authorization", "Basic YWRtaW46");
            StringEntity postingString = new StringEntity(json.toString(),"utf-8");
            post.setEntity(postingString);
            HttpResponse response = httpClient.execute(post);

            InputStream in = response.getEntity().getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
            StringBuilder strber= new StringBuilder();
            String line = null;
            while((line = br.readLine())!=null){
                strber.append(line+'\n');
            }
            br.close();
            in.close();
            result = strber.toString();
            if(response.getStatusLine().getStatusCode()!= HttpStatus.SC_OK){
                result = "服务器异常";
            }
        } catch (Exception e){
            System.out.println("请求异常");
            throw new RuntimeException(e);
        } finally{
            post.abort();
        }
        return result;
    }




    public String getShorUrl(String longUrl) {
        String shortUrl = null;

//        shortUrl = WeiBoDwzUtils.createShortUrl(longUrl);
        if (shortUrl == null || "".equals(shortUrl)) {
            shortUrl = createShortUrl(longUrl);
        }
        if (shortUrl == null || "".equals(shortUrl)) {
            shortUrl = BaiduDwzUtils.createShortUrl(longUrl, "1-year");
        }
        if (shortUrl == null || "".equals(shortUrl)) {
            shortUrl = SuoImDwzUtils.createShortUrl(longUrl);
        }
        if (shortUrl == null || "".equals(shortUrl)) {
            shortUrl = MrwSoDwzUtils.createShortUrl(longUrl);
        }
        if (shortUrl == null || "".equals(shortUrl)) {
            shortUrl = longUrl;
        }

        return shortUrl;
    }






    class UrlResponse {
        @SerializedName("errcode")
        private int errcode;

        @SerializedName("errmsg")
        private String errmsg;

        @SerializedName("short_url")
        private String short_url;

        public int getErrcode() {
            return errcode;
        }
        public String getErrmsg() {
            return errmsg;
        }
        public String getShort_url() {
            return short_url;
        }
    }


    @Override
    public String createShare1(String accesskey,String secretkey,String buckets,String qnysite,  String userName, String headUrl,
                                      String qrUrl,String imgName,String imgUrl) {
        String shareUrl = "";
        try {
            final String format = "png";

            //定义二维码的参数
            HashMap hints = new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "gbk");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            hints.put(EncodeHintType.MARGIN, 1);
            String imgStr = "";
            //生成二维码

            //OutputStream stream = new OutputStreamWriter();

            //URL url = new URL("http://127.0.0.1:8892/img/share2.jpg");省鸭
            URL url = new URL(imgUrl);
            BufferedImage image = ImageIO.read(url);
            Graphics2D g2 = image.createGraphics();
            /**
             * 读取Logo图片
             */
//            if(StringUtils.isNotEmpty(headUrl)){
//                url = new URL(headUrl);
//                BufferedImage logo = ImageIO.read(url);
//                g2.drawImage(logo, 80, 700, 80, 80, null);//绘制
//            }
            qrUrl = getShorUrl(qrUrl);//qrUrl 二维码内容  shortUrl 转短链  为了二维码图片更容易扫
            BufferedImage qr =  createQrImage(qrUrl,130,130);//生成二维码宽高
            g2.drawImage(qr,311 , 1055, 130, 130, null);//绘制
//          g2.drawImage(qr, 图片左边到二维码左边的距离, 图片顶部到二维码顶部的距离, 二维码在分享图片上的宽度（带白边）,高度, null);

            //往图片上绘制汉字  按需取用
//             Font f = new Font("微软雅黑",Font.PLAIN, 25);
//            Color mycolor = Color.black;//new Color(0, 0, 255);
//            g2.setColor(mycolor);
//            g2.setFont(f);
//            g2.drawString(userName, 195, 750);


            g2.dispose();
            image.flush();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", outputStream);
            String accessKey = accesskey;
            String secretKey = secretkey;
            String bucket = buckets;
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            Configuration cfg = new Configuration(Zone.zone2());
            //...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);
            //String key = imgName;
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(outputStream.toByteArray());
            Response response2 = uploadManager.put(byteInputStream, null, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response2.bodyString(), DefaultPutRet.class);
            shareUrl = qnysite + "/" + putRet.key;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return shareUrl;
    }

    private  BufferedImage createQrImage(String str, int width, int height) {
        BitMatrix bitMatrix = null;
        HashMap hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "gbk");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.MARGIN, 1);
        try {
            bitMatrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }
}
